﻿using System;
using System.Threading.Tasks;

namespace InDepth2Demo.Chapter15
{
    internal class Async_Tongyi
    {
        public static async Task CallAsync()
        {
            Console.WriteLine("Starting the program...");

            // 启动异步任务
            Task<int> task1 = PerformLongCalculationAsync(1, 3000); // 模拟耗时3秒的计算
            Task<int> task2 = PerformLongCalculationAsync(2, 2000); // 模拟耗时2秒的计算

            // 在等待异步任务完成的同时，执行一些同步任务
            Console.WriteLine("Performing some other work...");
            CountToALargeNumber(1, 5000000);
            CountToALargeNumber(2, 5000000);

            // 等待异步任务完成并获取结果
            int result1 = await task1;
            int result2 = await task2;

            Console.WriteLine($"Result from task 1: {result1}");
            Console.WriteLine($"Result from task 2: {result2}");

            Console.WriteLine("Program completed.");
        }

        // 异步方法：模拟耗时的计算任务
        private static async Task<int> PerformLongCalculationAsync(int taskId, int delayMilliseconds)
        {
            Console.WriteLine($"Task {taskId}: Starting calculation...");
            await Task.Delay(delayMilliseconds); // 模拟耗时操作
            int result = taskId * 10; // 简单的计算
            Console.WriteLine($"Task {taskId}: Calculation completed with result {result}.");
            return result;
        }

        // 同步方法：模拟长时间运行的任务（例如计数）
        private static void CountToALargeNumber(int id, int countTo)
        {
            for (long i = 0; i < countTo; i++)
            {
                // 这里可以放置一些实际的工作
            }
            Console.WriteLine($"Counting {id} completed.");
        }
    }
}
